﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MyBehaviorTree
{
    public class Parallel : Composite
    {
        public enum Policy
        {
            RequireOne,
            RequireAll
        }

        protected Policy successPolicy;
        protected Policy failurePolicy;

        public Parallel(Policy success,Policy failure)
        {
            successPolicy = success;
            failurePolicy = failure;
        }

        public override State update()
        {
            int successCount = 0;
            int failureCount = 0;

            foreach(var child in children)
            {
                if (!child.isEnd()) child.run();
                if (child.state == State.SUSCCESS)
                {
                    successCount++;
                    if (successPolicy == Policy.RequireOne)
                    {
                        child.reset();
                        return State.SUSCCESS;
                    }
                }
                if (child.state == State.FAILURE)
                {
                    failureCount++;
                    if (failurePolicy == Policy.RequireOne)
                    {
                        child.reset();
                        return State.FAILURE;
                    }
                }
            }

            if (failurePolicy == Policy.RequireAll && failureCount == children.Count)
                return State.FAILURE;
            if (successPolicy == Policy.RequireAll && successCount == children.Count)
                return State.SUSCCESS;

            return State.FAILURE;
        }

        public override void end()
        {
            base.end();
            foreach (var child in children)
            {
                if (child.state == State.RUNNING)
                {
                    child.abort();
                }
            }
        }
    }
}
